package com.nursebetty.droid.client.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.nursebetty.droid.client.model.BloodModel;
import com.nursebetty.droid.client.model.User;
import com.nursebetty.droid.client.model.UserHistory;
import com.nursebetty.droid.client.util.RestClient;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Blood extends Activity{
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blood);
        
        final User user = (User) getIntent().getExtras().get("user");
        
        
        Button bloodBtn = (Button)findViewById(R.id.bloodSaveBtn);
        final EditText bloodField = (EditText)findViewById(R.id.bloodField);
        bloodBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					JSONObject response = RestClient.connect("http://10.0.2.2:8080/nb/setBlood?id=" + user.getUserId()
															+ "&bval=" + bloodField.getText().toString());
					UserHistory uh = createBloodHistory(response);
					if (response != null){
						Intent i = new Intent(Blood.this, BloodHistory.class);
						Bundle b = new Bundle();
						b.putSerializable("user", user);
						b.putSerializable("userHistory", uh);
						i.putExtras(b);
						
						startActivity(i);
					}
					Log.i("info",response.toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			private UserHistory createBloodHistory(JSONObject json) {
				try {
					UserHistory uh = new UserHistory();
					List<BloodModel> gl = new ArrayList<BloodModel>(); 
					JSONArray nameArray=json.names();
	                JSONArray valArray=json.toJSONArray(nameArray);
	                for(int i=0;i<valArray.length();i++)
	                {
	                	JSONArray bloodArray = valArray.getJSONArray(i);
	                	for (int j = 0; j < bloodArray.length() ; j++){
		                	BloodModel bm= new BloodModel();
		                	JSONObject bloodEntry = bloodArray.getJSONObject(j);
		                	bm.setBloodValue(bloodEntry.getInt(bloodEntry.names().getString(0)));
		                	bm.setTestDate(bloodEntry.getString(bloodEntry.names().getString(1)));
		                	gl.add(bm);
	                	}
	                }
	                uh.setBloodHistory(gl);
	                return uh;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
        	
        	
        });
	}
}
